package com.ruoyi.tcp.handler;

/**
 * @author 蒋翔 SY100242
 * @date 2024/7/30 14:27
 * @email SY100242@hnlens.com
 */

import com.ruoyi.tcp.messager.CustomerMessageDecoder;
import com.ruoyi.tcp.messager.CustomerMessageEncoder;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import java.util.concurrent.TimeUnit;

/**
 * Netty 通道初始化
 *
 * @author qiding
 */
@Component
@RequiredArgsConstructor
public class ChannelInit extends ChannelInitializer<SocketChannel> {

    private final MessageHandler messageHandler;

    @Override
    protected void initChannel(SocketChannel channel) {
        channel.pipeline()
                // 心跳时间
                .addLast("idle", new IdleStateHandler(120, 0, 180, TimeUnit.SECONDS))
                // 添加解码器
                .addLast(new CustomerMessageDecoder())
                .addLast(new CustomerMessageEncoder())
//                .addLast(new StringDecoder())
                // 添加编码器
//                .addLast(new StringEncoder())
                // 添加消息处理器
                .addLast("messageHandler", messageHandler);
    }

}

